<?php
namespace common\components;

use Yii;
use function EasyWeChat\Kernel\Support\generate_sign;

class WeChatPayment{

    public static function getKey(){
        return Yii::$app->params['weixin']['payment_share']['key'];
    }

    /**
     * 预支付统一参数
     * @param array $attributes
     * @param string $encryptMethod
     * @return unknown
     */
    public static function generatePrePay(array $attributes, $encryptMethod = 'md5'){
        $encryptMethod              = self::getSignType($encryptMethod);
        $config                     = Yii::$app->params['weixin']['payment_share'];
        $attributes['appId']        = $config['app_id'];
        $attributes['timeStamp']    = (string)time();
        $attributes['nonceStr']     = uniqid();
        $attributes['signType']     = $encryptMethod;
        $attributes['paySign']      = generate_sign($attributes, self::getKey(), $encryptMethod);
        return $attributes;
    }

    public static function checkSign(array $attributes, $encryptMethod = 'md5'){
        $encryptMethod  = self::getSignType($encryptMethod);
        $sign           = $attributes['sign'];
        unset($attributes['sign']);
        $checkSign      = generate_sign($attributes, self::getKey(), $encryptMethod);
        return $sign === $checkSign;
    }

    public static function getSignType($signType){
        $secretKey = self::getKey();
        if ('HMAC-SHA256' === ($signType ?? 'MD5')) {
            $encryptMethod = function ($str) use ($secretKey) {
                return hash_hmac('sha256', $str, $secretKey);
            };
        } else {
            $encryptMethod = 'md5';
        }
        return $encryptMethod;
    }
}